/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.passport.controller  
 */
package com.apache.passport.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.passport.aop.LoginAopRunable;
import com.apache.passport.aop.PassportTheardPool;
import com.apache.passport.common.DesUtils;
import com.apache.passport.common.PassportHelper;
import com.apache.passport.entity.LoginInfo;
import com.apache.passport.entity.Token;
import com.apache.passport.entity.UctUser;
import com.apache.passport.manager.UctUserManager;

/**
 * description: 退出操作类 
 * @author Hou Dayu 创建时间：2014-12-22  
 * @Copyright(c)2014:
 */
@Controller
@RequestMapping({ "/passport/logout/" })
public class LogoutAction extends SsoBaseAction<UctUser> {
	@Autowired
	UctUserManager uctUserManager;
	private String COOKIENAME = SystemTools.getInstance().getValue("cookieName");

	/**
	 * description:  执行用户退出操作
	 * @param request
	 * @param response
	 * @param user
	 * @return  
	 * @author Hou Dayu 
	 * @update 2014-12-23
	 */
	@RequestMapping({ "logout.action" })
	@ResponseBody
	public ResultMsg logout(HttpServletRequest request, HttpServletResponse response, UctUser user) {
		ResultMsg rmsg = new ResultMsg("F", "用户退出操作失败");

		String tokenCookie = PassportHelper.getInstance().getCurrCookie(request);
		Token token = (Token) SystemTools.getInstance().getCache("loginToken").getCacheCloneByKey(tokenCookie);

		if (Validator.isEmpty(token)) {
			rmsg.setMsg("用户认证信息已失效");
			return rmsg;
		}

		//		LoggerVo logvo = getLoggerVo("用户退出", "用户[" + DesUtils.getInstance().decrypt(token.getUserEname()) + "]退出", "",
		//				"", "passport");

		String userEname = DesUtils.getInstance().decrypt(token.getUserEname());
		LoginInfo loginInfo = getLoginInfo(request, "passport", "", "passport", userEname, tokenCookie);
		ParamsVo<UctUser> vo = this.getParamsVo(request, null);
		vo.setMethodKey("logout");
		vo.setParams("loginInfo", loginInfo);
		vo.setObj(user);
		vo.setParams("tokenId", tokenCookie);
		vo.setParams("userEname", userEname);
		ResultEntity result = new ResultEntity();
		result = (ResultEntity) uctUserManager.execute(vo);
		if ("T".equals(result.getEntity())) {
			savelogInfo(loginInfo);
			rmsg.setFlag("T");
			rmsg.setMsg(result.getMessage());
			clearLoginInfo(request, response);
		} else {
			rmsg.setFlag("F");
			rmsg.setMsg(result.getMessage());
		}
		return rmsg;
	}

	/**
	 * 清空系统信息
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void clearLoginInfo(HttpServletRequest req, HttpServletResponse resp) {
		Cookie[] cookies = req.getCookies();
		try {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = new Cookie(cookies[i].getName(), null);
				cookie.setMaxAge(0);
				cookie.setPath("/");//根据你创建cookie的路径进行填写    
				resp.addCookie(cookie);
			}
		} catch (Exception ex) {
		}
		ArrayList lst = new ArrayList();
		Enumeration enumer = req.getSession().getAttributeNames();
		while (enumer.hasMoreElements()) {
			lst.add(enumer.nextElement());
		}
		for (int i = 0; i < lst.size(); i++) {
			req.getSession().removeAttribute(lst.get(i).toString());
		}
	}

	@Override
	protected Object data(HttpServletRequest httpservletrequest, String s, String s1) {
		return null;
	}

	@Override
	protected BaseManager<UctUser> getBaseManager() {
		return null;
	}

	@Override
	protected String getPrefix() {

		return null;
	}

	private void savelogInfo(LoginInfo log) {
		LoginAopRunable runnable = new LoginAopRunable(log, "logout");
		PassportTheardPool.getInstance().saveLogger(runnable);
	}

	/**
	 * description: 封装信息对象 
	 * @param request
	 * @param lastSysEname 最后登录系统
	 * @param lastSysTime 最后登录系统时间
	 * @param sysEname 当前登录系统名称
	 * @param userEname 当前登录人
	 * @return  
	 * @author Hou Dayu 
	 * @update 2014-12-19
	 */
	private LoginInfo getLoginInfo(HttpServletRequest request, String lastSysEname, String lastSysTime,
			String sysEname, String userEname, String tokenId) {
		String lgnLastipaddress = PassportHelper.getInstance().getIpAddr(request);
		String header = request.getHeader("User-agent");
		String lgnLastdevice = "";
		if (!Validator.isNull(header)) {
			int beginIndex = header.indexOf("(") + 1;
			int endIndex = header.indexOf(")");
			lgnLastdevice = header.substring(beginIndex, endIndex);
		}
		LoginInfo loginInfo = new LoginInfo();

		loginInfo.setTokenId(tokenId);
		loginInfo.setSessionId(request.getSession().getId());
		loginInfo.setSysEname(sysEname);//当前登录系统
		loginInfo.setUserEname(userEname);//当前登录人
		if (lgnLastdevice.contains("iPhone") || lgnLastdevice.contains("iPad") || lgnLastdevice.contains("iPad")
				|| lgnLastdevice.contains("iTouch") || lgnLastdevice.contains("Mac")) {
			loginInfo.setLgnJudge("Apple");//品牌
		} else if (lgnLastdevice.contains("Android")) {
			loginInfo.setLgnJudge("Android");//品牌
		} else if (lgnLastdevice.contains("SymbianOS")) {
			loginInfo.setLgnJudge("SymbianOS");//品牌
		} else if (lgnLastdevice.contains("Windows")) {
			loginInfo.setLgnJudge("Windows");//品牌
		} else {
			loginInfo.setLgnJudge("未知品牌");//品牌
		}
		loginInfo.setLgnLastarea("未知地域");//地域
		loginInfo.setLgnLastdevice(lgnLastdevice);//介质
		loginInfo.setLgnLastipaddress(lgnLastipaddress);//ip地址
		if (Validator.isNull(lastSysEname)) {
			lastSysEname = "未知系统";
		}
		loginInfo.setLgnLastsys(lastSysEname);//最后登录系统
		if (Validator.isNull(lastSysTime)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			lastSysTime = sdf.format(new Date());
		}
		loginInfo.setLgnLasttime(lastSysTime);//最后登录时间
		return loginInfo;
	}
}
